package com.atguigu.springmvc.controller;

import com.atguigu.springmvc.bean.Address;

import com.atguigu.springmvc.bean.Person;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
public class ResponseTestController {

    // 会自动的把返回的对象转为json格式
//    @ResponseBody //把返回的内容。写到响应体中, 这个注解在类注解@RestController中已经定义了,这里就不用再写了
    @RequestMapping("/resp01")
    public Person resp01() {
        Person person = new Person();
        person.setUsername("kevin");
        person.setPassword("11556632");
        person.setCellphone("15999878423");
        person.setAgreement(true);
        Address address = new Address();
        address.setProvince("南善");
        address.setCity("徐汇");
        address.setArea("普陀");
        person.setAddress(address);
        String[] bobbies = {"篮球", "足球", "乒乓球"};
        person.setHobby(bobbies);
        person.setGrade("一年级");
        person.setSex("male");

        return person;
    }

    // 文件下载
    // 拿到整个响应数据（响应头、响应体、状态码）
    @RequestMapping("/download")
    public ResponseEntity<InputStreamResource> download() throws IOException {
        FileInputStream fis = new FileInputStream("E:\\bizhi\\v2-a16f760d69ccda7d30fa3cc52012f61a_r.jpg");
        String encode = URLEncoder.encode("bizhi.jpg", "UTF-8");
        InputStreamResource resource = new InputStreamResource(fis);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(fis.available())
                .header("Content-Disposition", "attachment;filename=" + encode)
                .body(resource);
    }
}
